<template>
  <div class="app-container">
    <div class="base-info">
      <div class="header">基本信息</div>
      <div class="contract-content">
        <el-form ref="form" :model="form" :rules="rules" label-width="auto" class="addDialog">
          <el-form-item label="农户姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入农户姓名"/>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="身份证号码" prop="certificateCode">
                <el-input v-model="form.certificateCode" placeholder="请输入身份证号码"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号" prop="mobile">
                <el-input v-model="form.mobile" placeholder="请输入手机号"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地块总个数" prop="landNum">
                <el-input v-model="form.landNum" placeholder="请输入地块总个数"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地块总面积" prop="landArea">
                <el-input v-model="form.landArea" placeholder="请输入地块总面积"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="作物种类" prop="agroProductType">
                <el-select v-model="form.agroProductType" placeholder="请选择作物种类">
                  <el-option v-for="dict in this.getDictDatas(DICT_TYPE.PRODUCE_INFO_CROP_SPECIE)" :key="dict.value"
                             :label="dict.label" :value="parseInt(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="土地类型" prop="landType">
                <el-select v-model="form.landType" placeholder="请选择土地类型">
                  <el-option v-for="dict in this.getDictDatas(DICT_TYPE.LAND_TYPE)" :key="dict.value"
                             :label="dict.label" :value="parseInt(dict.value)"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="land-info">
          <div class="header">种植地块信息</div>
          <dtsz-map ref="landMap" mapId="landMap" :contractSign="true" height="1000px" :polygonForm="landPolygonForm"
                    :polygonStyle="polygonStyle" @onChange="onPolygonChange" :center="[117.273643,31.505606]"/>
          <div class="area-list">
            <el-table :data="form.plantingInformationList" style="width: 100%" border>
              <el-table-column prop="plantingName" label="种植物名称" align="center" width="180"/>
              <el-table-column prop="landCode" label="地块编码" align="center" width="180"/>
              <!--              <el-table-column label="种植时间" align="center" prop="plantingCycle" width="180">-->
              <!--                <template v-slot="scope">-->
              <!--                  <span>{{ parseTime(scope.row.plantingTime) }}</span>-->
              <!--                </template>-->
              <!--              </el-table-column>-->
              <el-table-column prop="plantingCycle" label="种植周期(月)" align="center" width="180"/>
              <el-table-column prop="inputName" label="投入品名称" align="center" width="180"/>
              <el-table-column prop="cropYield" label="作物产量" align="center"/>
              <el-table-column prop="landInformation" label="土壤信息" align="center" width="180">
                <template v-slot="scope">
                  <dict-tag :type="DICT_TYPE.LAND_INFORMATION" :value="scope.row.landInformation"/>
                </template>
              </el-table-column>
              <el-table-column prop="pestsDiseases" label="病虫防治" align="center" width="180">
                <template v-slot="scope">
                  <dict-tag :type="DICT_TYPE.PESTS_DISEASES" :value="scope.row.pestsDiseases"/>
                </template>
              </el-table-column>
              <el-table-column prop="agroReviewStorageMethod" label="存储方式" align="center" width="180">
                <template v-slot="scope">
                  <dict-tag :type="DICT_TYPE.AGRO_REVIEW_STORAGE_METHOD" :value="scope.row.agroReviewStorageMethod"/>
                </template>
              </el-table-column>
            </el-table>
          </div>

        </div>
        <el-form style="text-align: center; margin-top: 20px">
          <el-form-item v-if="type !== 'look'">
            <el-button type="primary" @click="submitForm">确定</el-button>
            <el-button type="danger" @click="cancelForm">取消</el-button>
          </el-form-item>
        </el-form>
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
          <div slot="footer" class="dialog-footer">
            <el-button @click="upload.open = false">关 闭</el-button>
          </div>
        </el-dialog>

        <el-dialog title="农户列表" :visible.sync="farmerListOpen" width="800px" append-to-body
                   :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
          <el-table ref="farmerTable" :data="farmerList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"/>
            <el-table-column label="农户名" align="center" prop="name"/>
            <el-table-column label="手机号" align="center" prop="mobile"/>
            <el-table-column label="证件号码" align="center" prop="certificateCode"/>
            <el-table-column label="地块个数" align="center" prop="landNum"/>
            <el-table-column label="地块面积/亩" align="center" prop="landArea"/>
            <el-table-column label="所在地" align="center" prop="address"/>
          </el-table>
          <!-- 分页组件 -->
          <pagination v-show="farmerTotal > 0" :total="farmerTotal" :page.sync="queryParams.pageNo"
                      :limit.sync="queryParams.pageSize"/>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="handleCreateSelectFarmerLand">确 定</el-button>
            <el-button @click="farmerListOpen = false">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {createManagement, getManagement, updateManagement} from '@/api/farmer/management'
import DtszMap from '@/components/DtszMap'

export default {
  name: 'Edit-Management',
  components: {
    DtszMap
  },
  data() {
    return {
      // 页面类型
      type: 'edit',
      // 遮罩层
      loading: true,
      showEmployer: false,
      farmerListOpen: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        name: null,
        mobile: null,
        certificateCode: null
      },
      farmerTotal: 0,
      farmerList: [],
      selectFarmerList: [],
      employerData: {},
      // 表单参数
      form: {
        deleteIds: undefined
      },
      landPolygonForm: [
        {
          name: '种植物名称',
          field: 'plantingName'
        },
        // {
        //   name: "种植时间",
        //   field: "plantingTime",
        //   type:"date"
        // },
        {
          name: '投入品名称',
          field: 'inputName'
        },
        {
          name: '种植周期(月)',
          field: 'plantingCycle'
        },
        {
          name: '作物产量',
          field: 'cropYield'
        },
        {
          name: '地块编码',
          field: 'landCode'
        },
        {
          name: '土壤信息',
          field: 'landInformation',
          type: 'select',
          dictKey: 'LAND_INFORMATION'
        },
        {
          name: '病虫防治',
          field: 'pestsDiseases',
          type: 'select',
          dictKey: 'PESTS_DISEASES'
        },
        {
          name: '存储方式',
          field: 'agroReviewStorageMethod',
          type: 'select',
          dictKey: 'AGRO_REVIEW_STORAGE_METHOD'
        }
      ],
      polygonFormRules: {
        name: [{required: true, message: '农户姓名不能为空', trigger: 'blur'}],
        certificateCode: [{required: true, message: '证件号码不能为空', trigger: 'blur'}],
        mobile: [{required: true, message: '手机号不能为空', trigger: 'blur'}]
      },
      polygonStyle: {
        fillColor: '#409EFF', // 填充色
        fillOpacity: 0.2, // 填充透明度
        strokeColor: '#ff0000', // 轮廓颜色
        strokeWeight: 1, // 轮廓宽度
        strokeOpacity: 0.9 // 轮廓透明度
      },
      fileList: [],
      // 表单校验
      rules: {
        name: [
          {required: true, message: '农户姓名不能为空', trigger: 'blur'}
        ],
        certificateCode: [
          {required: true, message: '证件号码不能为空', trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '手机号不能为空', trigger: 'blur'}
        ]
      },
      // 用户导入参数
      upload: {
        open: false, // 是否显示弹出层
        title: '' // 弹出层标题
      }
    }
  },
  created() {
    this.type = this.$route.query.type
    const id = this.$route.query.id
    if (this.type !== 'add') {
      getManagement(id).then((response) => {
        const detailData = response.data
        this.form = {
          farmerCode: detailData.farmerCode,
          name: detailData.name,
          certificateCode: detailData.certificateCode,
          mobile: detailData.mobile,
          landNum: detailData.landNum,
          cropYield: detailData.cropYield,
          landArea: detailData.landArea,
          agroProductType: detailData.agroProductType,
          landType: detailData.landType,
          fileList: detailData.fileList,
          plantingInformationList: detailData.plantingInformationList,
          deleteIds: []
        }
        // 绘制地块区域
        if (this.form.plantingInformationList.length > 0) {
          // 地块区域加载
          this.form.plantingInformationList.forEach((v) => {
            let polygon = {
              id: v.id,
              parentId: v.id,
              // contractorCode: v.contractorCode,
              plantingName: v.plantingName,
              landCode: v.landCode,
              plantingTime: v.plantingTime,
              cropYield: v.cropYield,
              landArea: v.landArea,
              plantingCycle: v.plantingCycle,
              inputName: v.inputName,
              landInformation: v.landInformation,
              pestsDiseases: v.pestsDiseases,
              agroReviewStorageMethod: v.agroReviewStorageMethod,
              path: v.coordinates,
              farmerId: v.farmerId,
              styles: {
                fillColor: '#409EFF', // 填充色
                fillOpacity: 0.2, // 填充透明度
                strokeColor: '#ffff00', // 轮廓颜色
                // strokeColor: '#409EFF', // 轮廓颜色
                strokeWeight: 1, // 轮廓宽度
                strokeOpacity: 0.9, // 轮廓透明度
                text: v.plantingName + '\n' + v.landArea + ' 亩'
              }
            }
            this.$refs['landMap'].addPolygon(polygon)
          })
          this.$refs['landMap'].focusFeatureCenter()
        }
      })
    }
  },
  methods: {
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id
      getManagement(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改农户土地信息'
      })
    },
    handleSelectionChange(row) {
      this.selectFarmerList = row
    },
    // 为选中的农户创建地块图层
    handleCreateSelectFarmerLand() {
      this.farmerListOpen = false
      if (this.selectFarmerList) {
        this.selectFarmerList.forEach(farmer => {
          farmer.plantingInformationList.forEach(land => {
            const polygon = {
              id: land.id,
              path: land.coordinates,
              styles: {
                fillColor: '#409EFF', // 填充色
                fillOpacity: 0.2, // 填充透明度
                strokeColor: '#ffff00', // 轮廓颜色
                strokeWeight: 1, // 轮廓宽度
                strokeOpacity: 0.9 // 轮廓透明度
              }
            }
            this.$refs['landMap'].addOriginalPolygons(polygon)
          })
        })
        this.$refs['landMap'].focusFeatureCenter()
      }
    },
    /** 提交按钮 */
    submitForm() {
      Promise.all([
        // this.$refs["employerForm"].validate(),
        this.$refs['form'].validate()
        // this.$refs["picForm"].validate()
      ]).then(() => {
        //判断地块列表是否为空
        // if (this.form.plantingInformationList.length === 0) {
        //   this.$modal.msgWarning('地块列表不能为空')
        // }
        // 修改的提交
        if (this.type === 'edit') {
          updateManagement({
            id: this.$route.query.id,
            ...this.form
          }).then((response) => {
            this.$modal.msgSuccess('修改成功')
            this.$tab.closeOpenPage({path: '/farmer/management/index'})
          })
        } else if (this.type === 'add') {
          // 添加的提交
          createManagement(this.form).then((response) => {
            this.$modal.msgSuccess('新增成功')
            this.$tab.closeOpenPage({path: '/farmer/management/index'})
          })
        }
      })
    },
    /** 取消按钮 */
    cancelForm() {
      this.$tab.closeOpenPage({path: '/farmer/management/index'})
    },
    onPolygonChange(polygon) {
      //记录地图删除的ids
      if (polygon.operateType === "delete"){
        if (polygon.id !== null){
          this.form.deleteIds.push(polygon.id)
        }
      }
      const landList = polygon.polygons.map(item => {
        item.coordinates = item.path
        item.farmerLandId = item.parentId
        item.blockIds = item.parentIds
        if (typeof(item.id) === 'string'){
          item.id = null;
        }
        return item
      })
      this.form.plantingInformationList = Object.assign([], landList)
    }
  },
}
</script>
<style lang="scss" scoped>
.header {
  display: inline-block;
  padding: 10px;
  border-bottom: 2px solid #409eff;
  margin-bottom: 20px;
}

.title {
  margin-bottom: 20px;
  text-align: left;
}

.app-container {
  background-color: #f0f2f5;

  .base-info {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;

    .contract-content {
      margin-bottom: 20px;

      .el-form-item {
        ::v-deep .el-form-item__content {
          .el-date-editor {
            width: 150px;
          }
        }

        &.contractEndTime {
          color: red;

          ::v-deep .el-form-item__label {
            width: 20px !important;
          }
        }
      }

      .disable-area {
        .el-form-item {
          ::v-deep .el-form-item__content {
            width: 191px;
            height: 36px;
            line-height: 36px;
            background-color: #F5F7FA;
            border: 1px solid #dfe4ed;
            padding: 0 15px;
          }
        }
      }
    }
  }

  .land-info {
    background-color: #fff;
    padding: 20px;

    .area-list {
      margin-top: 20px;

      .title {
        span {
          margin-right: 30px;
        }
      }

      .el-table {
        margin-bottom: 20px;
      }
    }

    .file-list {
      margin-top: 20px;

      .title {
        margin-bottom: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
}
</style>
